package com.lmc.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import java.text.DecimalFormat;
import java.util.Arrays;

public class BrokenLine extends View {
    private String[] xLabel;//X轴刻度值
    private String[] data;//数据点
    private String[] data2;//数据点2
    private String[] data3;//数据点3
    private String[] yLabel;//Y坐标刻度值

    private Paint mDataLinePaint;//数据点连线画笔
    private Paint mScaleLinePaint;//坐村（刻度线条）画笔
    private Paint mScaleValuePaint;//图表（刻度值）画笔
    private Paint mBackColorPaint;//背景（色块）画笔

    private float yScale;//y轴刻度
    private float xScale;//x轴刻度
    float startPointX;//x坐标绘制
    float startPointY;//x坐标绘制
    float xLength;//x轴长度
    float yLength;//y轴长度
    float xTextPlaceHeight;//x轴文字高度
    float chartLineStrokeWidth;//图表线条的宽度
    float coordTextSize;//坐标刻度文字的大小
    float dataLineStrodeWidth;//数据线条的宽度

    String[] mDataLineColors;
    private Rect bounds;

    float[][] mDataCoords;
    float[][] mDataCoords2;
    float[][] mDataCoords3;
    boolean isClick;
    int clickIndex;
    private PopupWindow mPopWin;

    public String[] getyLabel() {
        return yLabel;
    }

    public void setyLabel(String[] yLabel) {
        this.yLabel = yLabel;
    }

    public String[] getxLabel() {
        return xLabel;
    }

    public void setxLabel(String[] xLabel) {
        this.xLabel = xLabel;
    }

    public String[] getData() {
        return data;
    }

    public void setData(String[] data) {
        this.data = data;
        setColor();
        initParams();
    }

    public void setData(String[] data, String[] data2) {
        this.data = data;
        this.data2 = data2;
        setColor();
        initParams();
    }

    public void setData(String[] data, String[] data2, String[] data3) {
        this.data = data;
        this.data2 = data2;
        this.data3 = data3;
        setColor();
        initParams();
    }

    public BrokenLine(Context context) {
        this(context, null);
    }

    public BrokenLine(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BrokenLine(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init() {
        this.setBackgroundColor(Color.WHITE);
        // x轴刻度值
        if (xLabel == null) {
            xLabel = new String[]{"05/07", "05/08", "05/09", "05/10", "05/11", "05/12", "今天"};
        }
        // 数据点
        if (data == null) {
            data = new String[]{"0", "0", "0", "0", "0", "0", "0"};
        }

        // 根据设置的数据值生成Y坐标刻度值
        if (yLabel == null) {
            yLabel = new String[]{"-10", "0", "10", "20", "30"};
        }

        // 新建画笔
        mDataLinePaint = new Paint();       // 数据(点和连线)画笔
        mScaleLinePaint = new Paint();      // 坐标(刻度线条)值画笔
        mScaleValuePaint = new Paint();      // 图表(刻度值)画笔
        mBackColorPaint = new Paint();       // 背景(色块)画笔
        // 画笔抗锯齿
        mDataLinePaint.setAntiAlias(true);
        mScaleLinePaint.setAntiAlias(true);
        mScaleValuePaint.setAntiAlias(true);
        mBackColorPaint.setAntiAlias(true);
        bounds = new Rect();
        // 数据点及其连线的颜色集合
        setColor();
    }

    private void setColor() {
        mDataLineColors = new String[data.length];
        for (int i = 0; i < data.length; i++) {
            if (data[i].equals("-1")) {
                mDataLineColors[i] = "#00000000";
            } else {
                mDataLineColors[i] = "#FF2A8CFF";
            }
        }

        mDataCoords = new float[data.length][2];
        if (data2 != null) {
            mDataCoords2 = new float[data2.length][2];
        }
        if (data3 != null) {
            mDataCoords3 = new float[data3.length][2];
        }
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        initParams();
    }

    private void initParams() {
        Log.e("-----------", "initParams");
        int width = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
        int height = getMeasuredHeight() - getPaddingTop() - getPaddingBottom();

        yScale = height / (yLabel.length + 1.5f);         // y轴刻度
        xScale = width / (data.length + 0.5f);          // x轴刻度
        startPointX = 80;       // 开始绘图的x坐标

        startPointY = yScale / 2;       // 开始UI图的y坐标
        xLength = (data.length - 1 + 0.5f) * xScale;        // x轴长度
        yLength = (yLabel.length + 0.5f) * yScale;        // y轴长度
        xTextPlaceHeight = yScale / 2;       // x轴刻度文字的占位高度
        chartLineStrokeWidth = 2;     // 图表线条的线宽
        coordTextSize = 22;             // 坐标刻度文字的大小
        dataLineStrodeWidth = 4;      // 数据线条的线宽
        // 设置画笔相关属性
        mBackColorPaint.setColor(Color.parseColor("#ffffff"));
        mScaleLinePaint.setStrokeWidth(chartLineStrokeWidth);
        mScaleLinePaint.setColor(Color.parseColor("#FFE0E0E0"));
        mScaleValuePaint.setColor(Color.parseColor("#FF333333"));
        mScaleValuePaint.setTextSize(coordTextSize);
        mDataLinePaint.setStrokeWidth(dataLineStrodeWidth);
        mDataLinePaint.setStrokeCap(Paint.Cap.ROUND);
        mDataLinePaint.setTextSize(1.0f);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBackColor(canvas);              // 绘制背景色块
        drawYAxisAndXScaleValue(canvas);    // 绘制y轴和x刻度值
        drawXAxisAndYScaleValue(canvas);    // 绘制x轴和y刻度值
        drawDataLines(canvas);              // 绘制数据连线
        drawDataPoints(canvas);             // 绘制数据点

        if (data2 != null) {
            drawDataLines2(canvas);              // 绘制第二条数据连线
            drawDataPoints2(canvas);             // 绘制第二个数据点
        }
        if (data3 != null) {
            drawDataLines3(canvas);              // 绘制第三条数据连线
            drawDataPoints3(canvas);             // 绘制第三个数据点
        }
    }


    /**
     * 绘制背景色块
     *
     * @param canvas
     */
    private void drawBackColor(Canvas canvas) {
        for (int i = 0; i < data.length; i++) {

            if (i == 2 || i == (yLabel.length - 1) || i == (data.length - 1)) {
                canvas.drawRect(startPointX + (i - 1) * xScale,
                        startPointY,
                        startPointX + i * xScale,
                        yLength + startPointY,
                        mBackColorPaint);
            }
        }
    }

    private void drawYAxisAndXScaleValue(Canvas canvas) {
        for (int i = 0; i < data.length; i++) {
            canvas.drawLine(startPointX + i * xScale,
                    startPointY,
                    startPointX + i * xScale,
                    startPointY + yLength,
                    mScaleLinePaint);
            mScaleValuePaint.getTextBounds(xLabel[i], 0, xLabel[i].length(), bounds);
            if (i == 0) {
                canvas.drawText(xLabel[i],
                        startPointX,
                        startPointY + yLength + bounds.height() + yScale / 15,
                        mScaleValuePaint);
            } else {
                canvas.drawText(xLabel[i],
                        startPointX + i * xScale - bounds.width() / 2,
                        startPointY + yLength + bounds.height() + yScale / 15,
                        mScaleValuePaint);
            }
        }
    }

    /**
     * 绘制x轴和y刻度值
     *
     * @param canvas
     */
    private void drawXAxisAndYScaleValue(Canvas canvas) {
        for (int i = 0; i < yLabel.length + 1; i++) {
            if (i < (yLabel.length)) {
                mScaleValuePaint.getTextBounds(yLabel[(yLabel.length - 1) - i], 0, yLabel[(yLabel.length - 1) - i].length(), bounds);

                mScaleValuePaint.setTextAlign(Paint.Align.RIGHT);

                canvas.drawText(yLabel[(yLabel.length - 1) - i] + "   ",
                        startPointX + xScale / 15,
                        startPointY + yScale * (i + 0.5f) + bounds.height() / 2,
                        mScaleValuePaint);

                mScaleValuePaint.setTextAlign(Paint.Align.LEFT);

                canvas.drawLine(startPointX,
                        startPointY + (i + 0.5f) * yScale,
                        startPointX + xLength,
                        startPointY + (i + 0.5f) * yScale,
                        mScaleLinePaint);
            } else {

                canvas.drawLine(startPointX,
                        startPointY + (i + 0.5f) * yScale,
                        startPointX + xLength,
                        startPointY + (i + 0.5f) * yScale,
                        mScaleLinePaint);
            }
        }
    }

    /**
     * 绘制数据线条
     *
     * @param canvas
     */
    private void drawDataLines(Canvas canvas) {
        getDataRoords();
        for (int i = 0; i < data.length - 1; i++) {
            try {
                mDataLinePaint.setColor(Color.parseColor(mDataLineColors[i]));
                if (!data[i].equals("-1") && !data[i + 1].equals("-1")) {
                    canvas.drawLine(mDataCoords[i][0], mDataCoords[i][1], mDataCoords[i + 1][0], mDataCoords[i + 1][1], mDataLinePaint);
                }
            } catch (Exception e) {

            }

        }
    }

    /**
     * 绘制第二条数据线条
     *
     * @param canvas
     */
    private void drawDataLines2(Canvas canvas) {
        getDataRoords2();
        for (int i = 0; i < data2.length - 1; i++) {
            try {
                mDataLinePaint.setColor(Color.parseColor("#FF7200FF"));
                if (!data2[i].equals("-1") && !data2[i + 1].equals("-1")) {
                    canvas.drawLine(mDataCoords2[i][0], mDataCoords2[i][1], mDataCoords2[i + 1][0], mDataCoords2[i + 1][1], mDataLinePaint);
                }
            } catch (Exception e) {

            }

        }
    }

    /**
     * 绘制第三条数据线条
     *
     * @param canvas
     */
    private void drawDataLines3(Canvas canvas) {
        getDataRoords3();
        for (int i = 0; i < data3.length - 1; i++) {
            try {
                mDataLinePaint.setColor(Color.parseColor("#FF6390C8"));
                if (!data3[i].equals("-1") && !data3[i + 1].equals("-1")) {
                    canvas.drawLine(mDataCoords3[i][0], mDataCoords3[i][1], mDataCoords3[i + 1][0], mDataCoords3[i + 1][1], mDataLinePaint);
                }
            } catch (Exception e) {

            }

        }
    }

    /**
     * 绘制数据圆点
     *
     * @param canvas
     */
    private void drawDataPoints(Canvas canvas) {
        try {
            for (int i = 0; i < mDataLineColors.length; i++) {
                if (!data[i].equals("-1")) {
                    mDataLinePaint.setColor(Color.parseColor(mDataLineColors[i]));
                    canvas.drawCircle(mDataCoords[i][0], mDataCoords[i][1], 8, mDataLinePaint);
                    mDataLinePaint.setColor(Color.WHITE);
                    canvas.drawCircle(mDataCoords[i][0], mDataCoords[i][1], 4, mDataLinePaint);
                    mDataLinePaint.setColor(Color.parseColor(mDataLineColors[i]));
                }
            }

        } catch (Exception e) {

        }

    }

    /**
     * 绘制第二个数据圆点
     *
     * @param canvas
     */
    private void drawDataPoints2(Canvas canvas) {
        try {
            for (int i = 0; i < data2.length; i++) {
                if (!data2[i].equals("-1")) {
                    mDataLinePaint.setColor(Color.parseColor("#FF7200FF"));
                    canvas.drawCircle(mDataCoords2[i][0], mDataCoords2[i][1], 8, mDataLinePaint);
                    mDataLinePaint.setColor(Color.WHITE);
                    canvas.drawCircle(mDataCoords2[i][0], mDataCoords2[i][1], 4, mDataLinePaint);
                    mDataLinePaint.setColor(Color.parseColor("#FF7200FF"));
                }
            }

        } catch (Exception e) {

        }

    }

    /**
     * 绘制第三个数据圆点
     *
     * @param canvas
     */
    private void drawDataPoints3(Canvas canvas) {
        try {
            for (int i = 0; i < data3.length; i++) {
                if (!data3[i].equals("-1")) {
                    mDataLinePaint.setColor(Color.parseColor("#FF6390C8"));
                    canvas.drawCircle(mDataCoords3[i][0], mDataCoords3[i][1], 8, mDataLinePaint);
                    mDataLinePaint.setColor(Color.WHITE);
                    canvas.drawCircle(mDataCoords3[i][0], mDataCoords3[i][1], 4, mDataLinePaint);
                    mDataLinePaint.setColor(Color.parseColor("#FF6390C8"));
                }
            }

        } catch (Exception e) {

        }

    }

    /**
     * 获取数据值的坐标点
     *
     * @return 数据点的坐标
     */
    private void getDataRoords() {
        float originalPointX = startPointX;
        float originalPointY = startPointY + yLength - yScale;
        for (int i = 0; i < data.length; i++) {
            mDataCoords[i][0] = originalPointX + i * xScale;
            float dataY = Float.parseFloat(data[i]);
            float oriY = Float.parseFloat(yLabel[0]);
            mDataCoords[i][1] = originalPointY - (yScale * (dataY - oriY) / (Float.parseFloat(yLabel[1]) - Float.parseFloat(yLabel[0])));
        }
    }

    /**
     * 获取第二个数据值的坐标点
     *
     * @return 数据点的坐标
     */
    private void getDataRoords2() {
        float originalPointX = startPointX;
        float originalPointY = startPointY + yLength - yScale;
        for (int i = 0; i < data2.length; i++) {
            mDataCoords2[i][0] = originalPointX + i * xScale;
            float dataY = Float.parseFloat(data2[i]);
            float oriY = Float.parseFloat(yLabel[0]);
            mDataCoords2[i][1] = originalPointY - (yScale * (dataY - oriY) / (Float.parseFloat(yLabel[1]) - Float.parseFloat(yLabel[0])));
        }
    }

    /**
     * 获取第三个数据值的坐标点
     *
     * @return 数据点的坐标
     */
    private void getDataRoords3() {
        float originalPointX = startPointX;
        float originalPointY = startPointY + yLength - yScale;
        for (int i = 0; i < data3.length; i++) {
            mDataCoords3[i][0] = originalPointX + i * xScale;
            float dataY = Float.parseFloat(data3[i]);
            float oriY = Float.parseFloat(yLabel[0]);
            mDataCoords3[i][1] = originalPointY - (yScale * (dataY - oriY) / (Float.parseFloat(yLabel[1]) - Float.parseFloat(yLabel[0])));
        }
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float touchX = event.getX();
        float touchY = event.getY();
        for (int i = 0; i < data.length; i++) {
            float dataX = mDataCoords[i][0];
            float dataY = mDataCoords[i][1];
            // 控制触摸/点击的范围，在有效范围内才触发
            if (Math.abs(touchX - dataX) < xScale / 2 && Math.abs(touchY - dataY) < yScale / 2) {
                isClick = true;
                clickIndex = i;
                invalidate();     // 重绘展示数据点小圆圈
                if (!data[i].equals("-1")) {
                    showDetails(i);   // 通过PopupWindow展示详细数据信息
                }

                return true;
            } else {
                hideDetails();
            }
            clickIndex = -1;
            invalidate();
        }
        if (data2 != null) {
            for (int i = 0; i < data2.length; i++) {
                float dataX = mDataCoords2[i][0];
                float dataY = mDataCoords2[i][1];
                // 控制触摸/点击的范围，在有效范围内才触发
                if (Math.abs(touchX - dataX) < xScale / 2 && Math.abs(touchY - dataY) < yScale / 2) {
                    isClick = true;
                    clickIndex = i;
                    invalidate();     // 重绘展示数据点小圆圈
                    if (!data2[i].equals("-1")) {
                        showDetails2(i);   // 通过PopupWindow展示详细数据信息
                    }

                    return true;
                } else {
                    hideDetails();
                }
                clickIndex = -1;
                invalidate();
            }
        }

        if (data3 != null) {
            for (int i = 0; i < data3.length; i++) {
                float dataX = mDataCoords3[i][0];
                float dataY = mDataCoords3[i][1];
                // 控制触摸/点击的范围，在有效范围内才触发
                if (Math.abs(touchX - dataX) < xScale / 2 && Math.abs(touchY - dataY) < yScale / 2) {
                    isClick = true;
                    clickIndex = i;
                    invalidate();     // 重绘展示数据点小圆圈
                    if (!data3[i].equals("-1")) {
                        showDetails3(i);   // 通过PopupWindow展示详细数据信息
                    }

                    return true;
                } else {
                    hideDetails();
                }
                clickIndex = -1;
                invalidate();
            }
        }

        return super.onTouchEvent(event);
    }


    private void showDetails(int index) {
        if (mPopWin != null) {
            mPopWin.dismiss();
        }
        TextView tv = new TextView(getContext());
        tv.setTextColor(Color.parseColor("#FF2A8CFF"));
        tv.setGravity(Gravity.CENTER);
        tv.setText(data[index]);
        mPopWin = new PopupWindow(tv, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopWin.setBackgroundDrawable(new ColorDrawable(0));
        mPopWin.setFocusable(false);
        // 根据坐标点的位置计算弹窗的展示位置
        int xoff = (int) (mDataCoords[index][0] - 0.5f * xScale);
        int yoff = -(int) (getHeight() - mDataCoords[index][1] + 0.75f * yScale);
        mPopWin.showAsDropDown(this, xoff, yoff);
        mPopWin.update();
    }

    private void showDetails2(int index) {
        if (mPopWin != null) {
            mPopWin.dismiss();
        }
        TextView tv = new TextView(getContext());
        tv.setTextColor(Color.parseColor("#FF7200FF"));
        tv.setGravity(Gravity.CENTER);
        tv.setText(data2[index]);
        mPopWin = new PopupWindow(tv, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopWin.setBackgroundDrawable(new ColorDrawable(0));
        mPopWin.setFocusable(false);
        // 根据坐标点的位置计算弹窗的展示位置
        int xoff = (int) (mDataCoords2[index][0] - 0.5f * xScale);
        int yoff = -(int) (getHeight() - mDataCoords2[index][1] + 0.75f * yScale);
        mPopWin.showAsDropDown(this, xoff, yoff);
        mPopWin.update();
    }

    private void showDetails3(int index) {
        if (mPopWin != null) {
            mPopWin.dismiss();
        }
        TextView tv = new TextView(getContext());
        tv.setTextColor(Color.parseColor("#FF7200FF"));
        tv.setGravity(Gravity.CENTER);
        tv.setText(data3[index]);
        mPopWin = new PopupWindow(tv, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopWin.setBackgroundDrawable(new ColorDrawable(0));
        mPopWin.setFocusable(false);
        // 根据坐标点的位置计算弹窗的展示位置
        int xoff = (int) (mDataCoords3[index][0] - 0.5f * xScale);
        int yoff = -(int) (getHeight() - mDataCoords3[index][1] + 0.75f * yScale);
        mPopWin.showAsDropDown(this, xoff, yoff);
        mPopWin.update();
    }

    public void hideDetails() {
        if (mPopWin != null) mPopWin.dismiss();
    }

}
